package com.epam.cdp.ejb.singletons;

import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.AccessTimeout;
import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.DependsOn;
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.Singleton;
import javax.ejb.Startup;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

@Startup
@Singleton
@DependsOn("PaperLoaderBean")
@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER)
public class PrinterBean implements Printer {
	private final static Log log = LogFactory.getLog(PrinterBean.class);
	
	private int calloutNumber;
	
	@PostConstruct
	public static void beforeApplicationStartup() {
		log.info("Doing some printer preparation before application startup");
	}
	
	@PreDestroy
	public void afterApplicationShutdown() {
		log.info("Doing some preparation after application shutdown");
	}

	
	@Override
	@Lock(LockType.WRITE)
	@AccessTimeout(value = 5, unit = TimeUnit.SECONDS)
	public boolean print() {
	    boolean result = false;
		try {
			Thread.sleep(10000);
			result = true;
			calloutNumber++;
		} catch (InterruptedException e) {
			log.error("Failed to sleep thread");
		} finally {
		    return result;
		}
	}

	public int getCalloutNumber() {
	    return calloutNumber;
	}
	
	
	
}
